package com.serialstamper.api.wrapper.converters;


import com.serialstamper.api.wrapper.model.OrganizationData;
import com.serialstamper.api.wrapper.model.Quota;
import com.serialstamper.api.wrapper.model.Quota.QuotaPeriod;
import com.serialstamper.api.wrapper.model.Quota.QuotaType;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;

public class OrganizationDataConverter extends ModelConverter {
	
	public OrganizationDataConverter() {
		super(OrganizationData.class);
	}
	
	@Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		try {
			OrganizationData data = new OrganizationData();
	        while (reader.hasMoreChildren()) {
	            reader.moveDown();
	
	            String propertyName = reader.getNodeName();
	            if ("quotas".equals(propertyName)) {
	            	while (reader.hasMoreChildren()) {
		            	reader.moveDown();

		            	Quota q = new Quota();
	            		q.setType(Enum.valueOf(QuotaType.class, reader.getNodeName().toUpperCase()));

	            		reader.moveDown();
	            		q.setPeriod(Enum.valueOf(QuotaPeriod.class, reader.getValue()));
	            		reader.moveUp();
		            	reader.moveDown();
	            		q.setLimit(Long.parseLong(reader.getValue()));
	            		reader.moveUp();
		            	reader.moveDown();
	            		q.setUsed(Long.parseLong(reader.getValue()));
	            		reader.moveUp();

	            		reader.moveUp();
	            		
	            		data.getQuotas().put(q.getType(), q);
	            	}
	            }
	            else {
		            Object value = context.convertAnother(data, getFieldClass(propertyName));
		            setFieldValue(data, propertyName, value);
	            }
	            reader.moveUp();
	        }
	
	        return data;
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public String getAlias() {
		return "organizationData";
	}
}
